<script setup lang="ts">
import type { Address } from '@/types/mall'
import { validatePhone } from '@/utils/mall'

const router = useRouter()
const route = router.currentRoute.value

// 获取地址ID（编辑模式）
const addressId = route.query?.id as string

// 表单数据
const form = reactive({
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  postalCode: '',
  isDefault: false,
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入收货人姓名' }],
  phone: [
    { required: true, message: '请输入手机号' },
    { validator: (value: string) => validatePhone(value), message: '请输入正确的手机号' }
  ],
  province: [{ required: true, message: '请选择省份' }],
  city: [{ required: true, message: '请选择城市' }],
  district: [{ required: true, message: '请选择区县' }],
  detail: [{ required: true, message: '请输入详细地址' }],
}

// 地区选择器
const showRegionPicker = ref(false)
const regionColumns = ref([
  ['北京市', '上海市', '广东省', '浙江省', '江苏省'],
  ['北京市', '上海市', '深圳市', '杭州市', '南京市'],
  ['朝阳区', '海淀区', '浦东新区', '南山区', '西湖区'],
])

const loading = ref(false)
const isEditMode = computed(() => !!addressId)

// 获取地址详情
async function getAddressDetail() {
  if (!addressId) return

  try {
    loading.value = true
    
    // TODO: 调用API获取地址详情
    // const response = await api.address.getAddressDetail(addressId)
    // Object.assign(form, response.data)
    
    // 模拟数据
    Object.assign(form, {
      name: '张三',
      phone: '13800138000',
      province: '广东省',
      city: '深圳市',
      district: '南山区',
      detail: '科技园南区深圳湾科技生态园10栋A座',
      postalCode: '518000',
      isDefault: true,
    })
  } catch (error) {
    console.error('获取地址详情失败:', error)
    uni.showToast({ title: '获取地址失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 选择地区
function selectRegion() {
  showRegionPicker.value = true
}

// 确认选择地区
function onRegionConfirm({ value }: { value: string[] }) {
  form.province = value[0]
  form.city = value[1]
  form.district = value[2]
  showRegionPicker.value = false
}

// 保存地址
async function saveAddress() {
  try {
    // 表单验证
    const errors: string[] = []
    
    if (!form.name.trim()) errors.push('请输入收货人姓名')
    if (!form.phone.trim()) errors.push('请输入手机号')
    if (!validatePhone(form.phone)) errors.push('请输入正确的手机号')
    if (!form.province) errors.push('请选择省份')
    if (!form.city) errors.push('请选择城市')
    if (!form.district) errors.push('请选择区县')
    if (!form.detail.trim()) errors.push('请输入详细地址')
    
    if (errors.length > 0) {
      uni.showToast({ title: errors[0], icon: 'none' })
      return
    }

    loading.value = true
    
    const addressData = {
      name: form.name.trim(),
      phone: form.phone.trim(),
      province: form.province,
      city: form.city,
      district: form.district,
      detail: form.detail.trim(),
      postalCode: form.postalCode.trim(),
      isDefault: form.isDefault,
    }

    if (isEditMode.value) {
      // TODO: 调用API更新地址
      // await api.address.updateAddress(addressId, addressData)
      uni.showToast({ title: '更新成功', icon: 'success' })
    } else {
      // TODO: 调用API创建地址
      // await api.address.createAddress(addressData)
      uni.showToast({ title: '添加成功', icon: 'success' })
    }

    // 延迟返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } catch (error) {
    console.error('保存地址失败:', error)
    uni.showToast({ title: '保存失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 页面生命周期
onMounted(() => {
  if (isEditMode.value) {
    getAddressDetail()
  }
})
</script>

<template>
  <view class="address-edit-page">
    <wd-form>
      <!-- 收货人信息 -->
      <wd-cell-group title="收货人信息" border>
        <wd-input
          v-model="form.name"
          label="收货人"
          placeholder="请输入收货人姓名"
          clearable
          required
        />
        
        <wd-input
          v-model="form.phone"
          label="手机号"
          placeholder="请输入手机号"
          type="number"
          clearable
          required
        />
      </wd-cell-group>

      <!-- 收货地址 -->
      <wd-cell-group title="收货地址" border>
        <wd-cell
          title="所在地区"
          :value="form.province && form.city && form.district ? `${form.province} ${form.city} ${form.district}` : '请选择'"
          is-link
          required
          @click="selectRegion"
        />
        
        <wd-input
          v-model="form.detail"
          label="详细地址"
          placeholder="街道、门牌号等"
          type="textarea"
          :maxlength="100"
          show-word-limit
          required
        />
        
        <wd-input
          v-model="form.postalCode"
          label="邮政编码"
          placeholder="请输入邮政编码（选填）"
          type="number"
          clearable
        />
      </wd-cell-group>

      <!-- 其他设置 -->
      <wd-cell-group title="其他设置" border>
        <wd-cell title="设为默认地址">
          <template #right-icon>
            <wd-switch v-model="form.isDefault" />
          </template>
        </wd-cell>
      </wd-cell-group>
    </wd-form>

    <!-- 保存按钮 -->
    <view class="save-btn">
      <wd-button
        type="primary"
        size="large"
        block
        :loading="loading"
        @click="saveAddress"
      >
        {{ isEditMode ? '更新地址' : '保存地址' }}
      </wd-button>
    </view>

    <!-- 地区选择器 -->
    <wd-picker
      v-model="showRegionPicker"
      :columns="regionColumns"
      title="选择地区"
      @confirm="onRegionConfirm"
      @cancel="showRegionPicker = false"
    />
  </view>
</template>

<style lang="scss" scoped>
.address-edit-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100px;
}

.save-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px;
  background: white;
  border-top: 1px solid #f0f0f0;
}

:deep(.wd-cell-group) {
  margin-bottom: 10px;
}

:deep(.wd-input) {
  --wd-input-padding: 15px;
}

:deep(.wd-cell) {
  padding: 15px;
}
</style>

<route lang="json">
{
  "name": "addressEdit",
  "style": {
    "navigationBarTitleText": "编辑地址"
  }
}
</route>